<?php
namespace app\admin\controller;

use app\admin\model\AdminUser;
use app\admin\model\LoginNote;
use think\Controller;
use think\Request;

class Login extends Controller
{
    protected $user_model;
    protected $login_model;
    protected $request;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request = $request;

        // ini_set('session.cookie_domain', 'huwhois.cn');
        $this->user_model = new AdminUser();
        $this->login_model = new LoginNote();
    }

    public function index()
    {
        if ($this->request->isPOST()) {
            $param = $this->request->param();
            $username = trim($param['username']);
            $password = trim($param['pwd']);
            $verify = trim($param['verify']);

            if (!$username || !$password || !$verify) {
                $this->error('用户名/密码/验证码不能为空', '/login');
            }

            if (!$this->checkVerify($verify)) {
                $this->error('验证码不正确', '/login');
            }

            $info = $this->user_model->field('id,username,password,role_id,login_time,login_ip,status')
                ->where('username', $username)
                ->find();
                
            if (!$info || md5($password) != $info->password) {
                $this->error('用户名/密码不正确', '/login');
            }
            
            if ($info->status != 1) {
                $this->error('账户已停用, 请使用有效账号', '/login');
            }

            $time = time();

            $ip = inet_aton($this->request->ip());

            $result = $this->user_model->save([
                'login_time' => $time,
                'login_ip' => $ip,
            ], ['id' => $info->id]);

            if ($result === false) {
                $this->error('登陆失败,请稍后重试', '/login');
            }

            //记录登陆信息
            $browser = browse_info();

            @$this->login_model->save([
                'userid' => $info['id'],
                'time' => $time,
                'ip' => $ip,
                'browser' => $browser,
            ]);

            session('username', $info->username);
            session('uid', $info->id);
            session('role_id', $info->role_id);

            session('ltime', $info->login_time);
            session('lip', $info->login_ip);

            $this->success('登入成功', 'admin/index/index');
        } else {
            if (session('?user_name')) {
                $this->success('您已登入', 'admin/index/index');
            } else {
                return $this->fetch();
            }
        }
    }

    /**
     * 生成与检测验证码
     */
    public function makeCaptcha()
    {
        $captcha = new \think\captcha\Captcha();
        return $captcha->entry();
    }

    public function checkVerify($code)
    {
        $captcha = new \think\captcha\Captcha();
        return $captcha->check($code);
    }

    /**
     * 登出
     */
    public function logout()
    {
        session(null);
        $this->redirect('/login');
    }

    /**
     * 找回密码: 发送邮箱验证码->验证->重设
     */
    public function getPwd()
    {
        if (session('?user_name')) {
            $this->success('您已登入', '/index');
        }

        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $verify = trim($param['verify']);
            $username = trim($param['username']);

            if (!captcha_check($verify)) {
                $this->error('验证码不正确');
            }

            $data = $this->user_model->where('username', $username)->field('id, username, email')->find();
            if (!$data) {
                $this->error('用户名不存在');
            } else {
                if (!$data->email) {
                    $this->error('此账号未留存邮箱, 请联系管理员');
                } else {
                    \session('data', $data);   //用户信息存 session
                    return ['code'=>2];
                }
            }
        }

        return $this->fetch();
    }

    // 发送邮件
    public function emailVerify()
    {
        if (session('?user_name')) {
            $this->success('您已登入', '/index');
        }

        if (\session('?data') == false) {
            $this->error('用户名不能为空', '/forgot');
        }

        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $verify = trim($param['verify']);
            $email = trim($param['email']);

            if (!captcha_check($verify)) {
                $this->error('验证码不正确');
            }
            $data = session('data');
            if ($email != $data->email) {
                return $this->error('邮箱不正确');
            }

            $token = mt_rand(100000, 999999); // 6位数验证码

            $emailbody = "亲爱的" . $data->username . "：<br/>您正在使用邮箱找回密码。";
            $emailbody .= "<br/>验证码:<b>" . $token. "</b>请在操作页面输入此验证码完成邮箱验证。<br/>";
            $emailbody .= "验证密码4小时内有效。<br/><br/><br/><p style='text-align:left'>-------- huwhois敬上</p>";

            $result = send_email($email, '重置密码', $emailbody);

            if ($result == 1) {
                session('token', $token);
               
                return ['code'=>2];
            } else {
                $this->error('验证码获取失败');
            }
        } else {
            return $this->fetch();
        }
    }

    // 重设密码
    public function resetPwd()
    {
        if (session('?user_name')) {
            $this->success('您已登入', '/index');
        }

        if (\session('?data') == false or \session('?token') == false) {
            \session(null);
            return $this->error('用户名不能为空', '/forgot');
        }

        if ($this->request->isPost()) {
            $data = session('data');
            $token = session('token');

            $param = $this->request->param();

            if (is_null($param['verify']) or is_null($param['newpwd']) or is_null($param['renewpwd'])) {
                $this->error('验证码 or 密码不可为空');
            }
            
            if ($param['newpwd'] != $param['renewpwd']) {
                $this->error('两次密码不一致');
            }

            if ($param['verify'] != $token) {
                $this->error('验证码不正确');
            }

            $pwd = md5(trim($param['newpwd']));
            $id = $data->id;

            $result = $this->user_model->save(['password' => $pwd], ['id' => $id]);
            if ($result === false) {
                $this->error('重置失败, 请稍后重试');
            } else {
                \session(null);
                $this->success('密码设置成功, 请登录', '/login');
            }
        }
        return $this->fetch();
    }
}